package com.example.apitesttool.service;

import dev.langchain4j.agent.tool.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * RAG 增强的智能查询工具
 * 提供基于语义搜索的智能接口查询功能
 */
@Service
public class RagQueryTools {
    
    private static final Logger logger = LoggerFactory.getLogger(RagQueryTools.class);
    
    @Autowired
    private VectorDatabaseService vectorDatabaseService;
    
    @Autowired
    private OpenApiDocumentManager documentManager;
    
    /**
     * 智能搜索接口信息
     */
    @Tool("智能搜索接口信息")
    public String searchApiEndpoints(String query) {
        try {
            logger.info("执行智能接口搜索: {}", query);
            
            List<VectorDatabaseService.SearchResult> results = vectorDatabaseService.search(query, 1);
            
            if (results.isEmpty()) {
                return "未找到与查询相关的接口信息。请尝试使用不同的关键词或检查是否已上传相关文档。";
            }
            
            StringBuilder response = new StringBuilder();
            response.append("找到以下相关接口信息：\n\n");
            
            for (int i = 0; i < results.size(); i++) {
                VectorDatabaseService.SearchResult result = results.get(i);
                VectorDatabaseService.VectorDocument doc = result.getDocument();
                
                response.append(String.format("%d. ", i + 1));
                
                // 根据文档类型格式化输出
                String type = (String) doc.getMetadata().get("type");
                if ("api_endpoint".equals(type)) {
                    String method = (String) doc.getMetadata().get("method");
                    String path = (String) doc.getMetadata().get("path");
                    String summary = (String) doc.getMetadata().get("summary");
                    
                    response.append(String.format("**%s %s**", method, path));
                    if (summary != null) {
                        response.append(String.format(" - %s", summary));
                    }
                    response.append(String.format(" (相似度: %.2f)", result.getSimilarity()));
                    response.append("\n");
                    
                    // 添加部分内容预览
                    String content = doc.getContent();
                    String[] lines = content.split("\n");
                    for (int j = 0; j < Math.min(3, lines.length); j++) {
                        if (!lines[j].trim().isEmpty()) {
                            response.append("   ").append(lines[j]).append("\n");
                        }
                    }
                } else {
                    response.append(doc.getContent().substring(0, Math.min(200, doc.getContent().length())));
                    if (doc.getContent().length() > 200) {
                        response.append("...");
                    }
                    response.append(String.format(" (相似度: %.2f)", result.getSimilarity()));
                }
                
                response.append("\n\n");
            }
            
            return response.toString();
        } catch (Exception e) {
            logger.error("智能搜索失败", e);
            return "搜索过程中发生错误: " + e.getMessage();
        }
    }
    
    /**
     * 获取接口详细信息
     */
    @Tool("获取接口详细信息")
    public String getEndpointDetails(String path, String method) {
        try {
            logger.info("获取接口详细信息: {} {}", method, path);
            
            // 构建搜索查询
            String query = String.format("接口路径: %s HTTP 方法: %s", path, method);
            List<VectorDatabaseService.SearchResult> results = vectorDatabaseService.search(query, 3);
            
            // 寻找最匹配的结果
            VectorDatabaseService.SearchResult bestMatch = null;
            for (VectorDatabaseService.SearchResult result : results) {
                Map<String, Object> metadata = result.getDocument().getMetadata();
                if ("api_endpoint".equals(metadata.get("type")) &&
                    method.equalsIgnoreCase((String) metadata.get("method")) &&
                    path.equals(metadata.get("path"))) {
                    bestMatch = result;
                    break;
                }
            }
            
            if (bestMatch == null && !results.isEmpty()) {
                bestMatch = results.get(0);
            }
            
            if (bestMatch == null) {
                return String.format("未找到接口 %s %s 的详细信息", method, path);
            }
            
            return bestMatch.getDocument().getContent();
        } catch (Exception e) {
            logger.error("获取接口详细信息失败", e);
            return "获取接口详细信息时发生错误: " + e.getMessage();
        }
    }
    
    /**
     * 搜索数据模型
     */
    @Tool("搜索数据模型")
    public String searchDataModels(String modelName) {
        try {
            logger.info("搜索数据模型: {}", modelName);
            
            String query = "数据模型 模型名称 " + modelName;
            List<VectorDatabaseService.SearchResult> results = vectorDatabaseService.search(query, 3);
            
            if (results.isEmpty()) {
                return "未找到相关的数据模型定义";
            }
            
            StringBuilder response = new StringBuilder();
            response.append("找到以下相关数据模型：\n\n");
            
            for (VectorDatabaseService.SearchResult result : results) {
                if ("data_models".equals(result.getDocument().getMetadata().get("type"))) {
                    response.append(result.getDocument().getContent()).append("\n");
                    break;
                }
            }
            
            return response.toString();
        } catch (Exception e) {
            logger.error("搜索数据模型失败", e);
            return "搜索数据模型时发生错误: " + e.getMessage();
        }
    }
    
    /**
     * 获取服务器信息
     */
    @Tool("获取服务器信息")
    public String getServerInfo() {
        try {
            logger.info("获取服务器信息");
            
            String query = "服务器地址 API 基本信息";
            List<VectorDatabaseService.SearchResult> results = vectorDatabaseService.search(query, 3);
            
            for (VectorDatabaseService.SearchResult result : results) {
                if ("api_info".equals(result.getDocument().getMetadata().get("type"))) {
                    String content = result.getDocument().getContent();
                    String[] lines = content.split("\n");
                    for (String line : lines) {
                        if (line.contains("服务器地址")) {
                            return line;
                        }
                    }
                }
            }
            
            return "未找到服务器地址信息";
        } catch (Exception e) {
            logger.error("获取服务器信息失败", e);
            return "获取服务器信息时发生错误: " + e.getMessage();
        }
    }
    
    /**
     * 智能推荐相关接口
     */
    @Tool("智能推荐相关接口")
    public String recommendRelatedEndpoints(String currentOperation) {
        try {
            logger.info("推荐相关接口: {}", currentOperation);
            
            List<VectorDatabaseService.SearchResult> results = vectorDatabaseService.search(currentOperation, 8);
            
            if (results.isEmpty()) {
                return "暂无相关接口推荐";
            }
            
            StringBuilder response = new StringBuilder();
            response.append("基于当前操作，推荐以下相关接口：\n\n");
            
            Set<String> addedEndpoints = new HashSet<>();
            int count = 0;
            
            for (VectorDatabaseService.SearchResult result : results) {
                if (count >= 5) break;
                
                Map<String, Object> metadata = result.getDocument().getMetadata();
                if ("api_endpoint".equals(metadata.get("type"))) {
                    String method = (String) metadata.get("method");
                    String path = (String) metadata.get("path");
                    String endpoint = method + " " + path;
                    
                    if (!addedEndpoints.contains(endpoint)) {
                        addedEndpoints.add(endpoint);
                        String summary = (String) metadata.get("summary");
                        
                        response.append(String.format("- **%s** %s", method, path));
                        if (summary != null) {
                            response.append(String.format(" - %s", summary));
                        }
                        response.append("\n");
                        count++;
                    }
                }
            }
            
            return response.toString();
        } catch (Exception e) {
            logger.error("推荐相关接口失败", e);
            return "推荐相关接口时发生错误: " + e.getMessage();
        }
    }
    
    /**
     * 获取向量数据库统计信息
     */
    @Tool("获取向量数据库统计信息")
    public String getVectorDatabaseStats() {
        try {
            Map<String, Object> stats = vectorDatabaseService.getStats();
            StringBuilder response = new StringBuilder();
            response.append("向量数据库统计信息：\n");
            response.append(String.format("- 文档数量: %s\n", stats.get("totalDocuments")));
            response.append(String.format("- 向量块数量: %s\n", stats.get("totalChunks")));
            response.append(String.format("- 向量维度: %s\n", stats.get("embeddingDimension")));
            return response.toString();
        } catch (Exception e) {
            logger.error("获取统计信息失败", e);
            return "获取统计信息时发生错误: " + e.getMessage();
        }
    }
}

